package cn.allin.me.enums;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public interface IEnumSerializer {

    String ENUM_CLASS = "java.lang.Enum";

    @JsonValue
    default Object serialize() {
        Map<String, Object> data = Maps.newHashMap();
        if (!Objects.equals(ENUM_CLASS, this.getClass().getSuperclass().getName())) {
            return data;
        }
        data.put("constant", ((Enum<?>) this).name());
        List<String> methodsName = ReflectUtils.getMethods(this.getClass())
                .stream().map(Method::getName)
                .filter(it -> it.startsWith("get")
                        && !Objects.equals(it, "getDeclaringClass")
                        && !Objects.equals("getClass", it))
                .collect(Collectors.toList());
        methodsName.forEach(methodName -> {
            String fieldName = StringHelper.lowerFirst(methodName.substring(3));
            boolean contains = ReflectUtils.containsField(this.getClass(), fieldName);
            if (contains) {
                data.put(fieldName, ReflectUtils.invokeGetterMethod(this, fieldName));
            }
        });
        return data;
    }
}
